<template>
  <div class="appointment-container">
    <!-- 搜索筛选区域 -->
    <div class="search-area">
      <el-form :inline="true">
        <el-form-item label="患者姓名">
          <el-input v-model="searchForm.name" placeholder="请输入患者姓名" clearable />
        </el-form-item>
        <el-form-item label="预约状态">
          <el-select v-model="searchForm.status" placeholder="请选择" clearable>
            <el-option label="待处理" value="PENDING" />
            <el-option label="已拒绝" value="REJECTED" />
            <el-option label="已超时" value="TIMEOUT" />
          </el-select>
        </el-form-item>
        <el-form-item label="预约日期">
          <el-date-picker
            v-model="searchForm.startDate"
            type="date"
            placeholder="开始日期"
            format="YYYY/MM/DD"
            value-format="YYYY-MM-DD"
          />
          <span class="date-separator">至</span>
          <el-date-picker
            v-model="searchForm.endDate"
            type="date"
            placeholder="结束日期"
            format="YYYY/MM/DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetForm">重置</el-button>
          <el-button type="success" @click="markAllAsRead">全部已读</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 预约卡片展示区域 -->
    <div class="appointment-list" v-loading="loading">
      <el-empty v-if="appointmentList.length === 0" description="暂无预约数据" />
      <el-row :gutter="20" v-else>
        <el-col v-for="(item, index) in appointmentList" :key="index" :span="8">
          <appointment-card
            :appointment="item"
            @show-detail="showDetail"
            @start-consultation="startConsultation"
            @reject-appointment="rejectAppointment"
            @mark-as-read="handleMarkAsRead"
            @delete-appointment="deleteAppointment"
          />
        </el-col>
      </el-row>
    </div>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="total"
        :page-sizes="[10, 20, 30, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElLoading } from 'element-plus'
import { getDoctorAppointments, acceptAppointment, rejectAppointment as rejectAppointmentAPI, deleteAppointment as deleteAppointmentAPI } from '@/apis/doctor/doctorAppointmentAPI'
import type { DoctorAppointmentVO } from '@/apis/doctor/doctorAppointmentAPI'
import { useDoctorStore } from '@/stores/doctor'
import AppointmentCard from './AppointmentCard.vue'

// 初始化doctorStore
const doctorStore = useDoctorStore()

// 搜索表单数据
const searchForm = reactive({
  name: '',
  gender: '',
  status: '',
  startDate: '',
  endDate: ''
})

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const loading = ref(false)

// 预约列表数据
const appointmentList = ref<Array<{
  id: number;
  userId: number;
  patientName: string;
  phone: string;
  status: string;
  appointmentTime?: string;
  createTime: string;
  expireTime: string;
  rejectTime: string | null;
  isRead: boolean;
  avatar?: string;
  gender?: string;
  age?: number;
  department?: string;
  doctorName?: string;
}>>([])

// 获取预约列表数据
const fetchAppointmentList = async () => {
  loading.value = true
  try {
    // 从doctorStore中获取医生ID
    const doctorId = doctorStore.doctorId || ''

    if (!doctorId) {
      ElMessage.error('未获取到医生ID，请重新登录')
      return
    }

    const params = {
      doctorId: doctorId.toString(), // 确保转换为字符串
      pageNum: currentPage.value.toString(),
      pageSize: pageSize.value.toString(),
      name: searchForm.name || undefined,
      status: searchForm.status || undefined,
      startDate: searchForm.startDate || undefined,
      endDate: searchForm.endDate || undefined
    }

    const res = await getDoctorAppointments(params)

    if (res.status === 200) {
      total.value = res.data.total

      // 转换后端数据格式为前端显示格式
      appointmentList.value = res.data.records.map((item: DoctorAppointmentVO) => ({
        id: item.id, // 添加预约ID
        userId: item.userId, // 添加患者用户ID
        patientName: item.name,
        phone: item.phone,
        status: mapStatusFromBackend(item.status),
        createTime: item.createTime,
        expireTime: item.expireTime,
        rejectTime: item.rejectTime,
        appointmentTime: item.createTime, // 使用创建时间作为预约时间
        isRead: false, // 默认未读
        avatar: '', // 默认空头像
        gender: '', // 性别信息可能需要从其他接口获取
        age: 0, // 年龄信息可能需要从其他接口获取
        department: '', // 科室信息可能需要从其他接口获取
        doctorName: '' // 医生姓名可能需要从其他接口获取
      }))
    } else {
      ElMessage.error('获取预约列表失败')
    }
  } catch (error) {
    console.error('获取预约列表出错:', error)
    ElMessage.error('获取预约列表出错')
  } finally {
    loading.value = false
  }
}

// 后端状态映射到前端状态
const mapStatusFromBackend = (backendStatus: string): string => {
  // 保留原始状态值，同时提供映射以兼容现有代码
  return backendStatus
}

// 获取状态对应的样式类
const getStatusClass = (status: string) => {
  return {
    'status-waiting': status === 'waiting' || status === 'PENDING',
    'status-ongoing': status === 'ongoing',
    'status-cancelled': status === 'cancelled' || status === 'REJECTED' || status === 'TIMEOUT',
    'status-completed': status === 'completed'
  }
}

// 获取状态对应的类型
const getStatusType = (status: string) => {
  const statusMap: Record<string, string> = {
    waiting: 'info',
    ongoing: 'success',
    cancelled: 'danger',
    completed: 'warning',
    PENDING: 'info',
    REJECTED: 'danger',
    TIMEOUT: 'danger'
  }
  return statusMap[status] || 'info'
}

// 获取状态对应的文本
const getStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    waiting: '等待中',
    ongoing: '进行中',
    cancelled: '已取消',
    completed: '已完成',
    PENDING: '待处理',
    REJECTED: '已拒绝',
    TIMEOUT: '已超时'
  }
  return statusMap[status] || '未知状态'
}

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1
  fetchAppointmentList()
}

// 重置表单
const resetForm = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key as keyof typeof searchForm] = ''
  })
  handleSearch()
}

// 导入预约store
import { useAppointmentStore } from '@/stores/appointment'

// 初始化预约store
const appointmentStore = useAppointmentStore()

// 查看详情
const showDetail = (item: any) => {
  // 将当前预约信息保存到store中
  appointmentStore.setCurrentAppointment({
    id: item.id,
    userId: item.userId,
    patientName: item.patientName,
    status: item.status,
    createTime: item.createTime,
    expireTime: item.expireTime
  })
  console.log('查看详情：', item)
  // 这里可以添加导航到详情页面的逻辑
}

// 开始接诊
const startConsultation = async (item: any) => {
  try {
    // 获取预约ID
    const appointmentId = item.id
    if (!appointmentId) {
      ElMessage.warning('预约ID不存在，无法接诊')
      return
    }

    const res = await acceptAppointment(appointmentId)
    if (res.status === 200) {
      ElMessage.success('接诊成功')
      // 刷新列表
      fetchAppointmentList()
    } else {
      ElMessage.error(res.message || '接诊失败')
    }
  } catch (error) {
    console.error('接诊出错:', error)
    ElMessage.error('接诊出错')
  }
}

// 拒绝预约
const rejectAppointment = async (item: any) => {
  try {
    // 获取预约ID
    const appointmentId = item.id
    if (!appointmentId) {
      ElMessage.warning('预约ID不存在，无法拒绝')
      return
    }

    const res = await rejectAppointmentAPI(appointmentId)
    if (res.code === 200 || res.status === 200) {
      ElMessage.success('已拒绝预约')
      // 刷新列表
      fetchAppointmentList()
    } else {
      ElMessage.error(res.message || '拒绝预约失败')
    }
  } catch (error) {
    console.error('拒绝预约出错:', error)
    ElMessage.error('拒绝预约出错')
  }
}

// 分页大小改变
const handleSizeChange = (val: number) => {
  pageSize.value = val
  fetchAppointmentList()
}

// 当前页改变
const handleCurrentChange = (val: number) => {
  currentPage.value = val
  fetchAppointmentList()
}

// 标记全部已读
const markAllAsRead = () => {
  // 更新所有未读消息状态
  appointmentList.value = appointmentList.value.map(item => ({
    ...item,
    isRead: true
  }))
  // 提示用户操作成功
  ElMessage.success('已将所有消息标记为已读')
  // 实际项目中可能需要调用API将所有消息标记为已读
}

// 标记单个预约为已读
const handleMarkAsRead = (item: any) => {
  item.isRead = true
  ElMessage.success('已标记为已读')
  // 实际项目中可能需要调用API将单个消息标记为已读
}

// 删除预约
const deleteAppointment = async (item: any) => {
  try {
    // 获取预约ID
    const appointmentId = item.id
    if (!appointmentId) {
      ElMessage.warning('预约ID不存在，无法删除')
      return
    }

    // 调用删除API
    const res = await deleteAppointmentAPI({
      appointmentIds: [appointmentId]
    })

    if (res.status === 200) {
      ElMessage.success('删除预约成功')
      // 刷新列表
      fetchAppointmentList()
    } else {
      ElMessage.error(res.message || '删除预约失败')
    }
  } catch (error) {
    console.error('删除预约出错:', error)
    ElMessage.error('删除预约出错')
  }
}

// 初始化加载数据
onMounted(() => {
  fetchAppointmentList()
})
</script>

<style scoped>
.appointment-container {
  padding: 20px;
}

.search-area {
  background: #f5f7fa;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
}

.appointment-list {
  margin-bottom: 20px;
}

/* 卡片样式已移至AppointmentCard.vue组件 */

.pagination {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}
</style>
